//
//  LPPProductController.m
//  Lottery
//
//  Created by 刘盼 on 16/1/23.
//  Copyright © 2016年 lhheh. All rights reserved.
//

#import "LPPProductController.h"
#import "LPPProductModel.h"
#import "LPPProductCell.h"
@interface LPPProductController ()<UICollectionViewDataSource>

@property(nonatomic,strong)NSArray *products;
@end

@implementation LPPProductController

static NSString * const reuseIdentifier = @"Cell";

-(NSArray *)products {
    
    if (!_products) {
        
        NSString *path = [[NSBundle mainBundle]pathForResource:@"more_project" ofType:@"json"];
        
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        NSArray *tempArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
        
        NSMutableArray *array = [NSMutableArray array];
        //字典转模型
        for (NSDictionary *dict in tempArray) {
            
            LPPProductModel *model = [LPPProductModel productWithDictionary:dict];
            
            [array addObject:model];
        }
        _products = array;
    }
    return _products;
}
#pragma mark---------重写初始化方法----------

-(instancetype)init{
    
    return [self loadLayout];
}

-(instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout {
    
    return [self loadLayout];
}

-(instancetype)loadLayout {
   
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //cell大小
    layout.itemSize = CGSizeMake(80, 80);
    //cell间距
    layout.minimumInteritemSpacing = 0;
    //行距
    layout.minimumLineSpacing = 16;
    
    layout.sectionInset = UIEdgeInsetsMake(16, 0, 0, 0);
    
    return [super initWithCollectionViewLayout:layout];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UINib *nib = [UINib nibWithNibName:@"LPPProductCell" bundle:nil];
    
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentifier];
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.94 alpha:1];
}

#pragma mark---------<UICollectionViewDataSource>-----

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.products.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LPPProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    LPPProductModel *model = self.products[indexPath.item];
    
    cell.model = model;
    
    return cell;
}
@end
